package impl

import (
	"context"
	uuid2 "github.com/google/uuid"
	"path"
	"strings"
	"user-web/src/api"
	"user-web/src/biz"
	"user-web/src/request"
	"user-web/src/response"
	"user-web/src/service"
	"user-web/src/util"
	"user-web/src/util/logs"
	pb "user-web/user"
)

const (
	UploadPath = "static/upload/"
)

var FileExt = []string{
	".jpg",
	".png",
}

func init() {
	biz.InjectUserService(&UserServiceImpl{})
}

type UserServiceImpl struct {
}

//Login 用户登录接口
func (us *UserServiceImpl) Login(loginRequest *request.LoginRequest) *api.JsonResult {
	username := loginRequest.Username
	password := loginRequest.Password

	client := service.UserService

	var ctx = context.Background()
	resp, _ := client.Login(ctx, &pb.LoginRequest{
		Username: username,
		Passwd:   password,
	})
	if resp.Code != api.SUCCESS {
		return api.Json(int(resp.Code), resp.Msg, nil)
	}

	token, _ := util.GeneratorJwt(username)
	refreshToken, _ := util.GeneratorRefreshJwt(username)

	loginResponse := response.LoginResponse{
		Username:     username,
		Token:        token,
		RefreshToken: refreshToken,
	}
	return api.JsonData(loginResponse)
}

//Query 用户查询接口
func (us *UserServiceImpl) Query(infoRequest *request.InfoRequest) *api.JsonResult {
	username := infoRequest.Username

	client := service.UserService

	var ctx = context.Background()
	resp, _ := client.GetUserInfo(ctx, &pb.CommonRequest{
		Username: username,
	})
	if resp.Code != api.SUCCESS {
		return api.Json(int(resp.Code), resp.Msg, nil)
	}

	userInfoResponse := response.UserInfoResponse{
		Username: username,
		Nickname: resp.Nickname,
		Profile:  resp.Profile,
	}
	return api.JsonData(userInfoResponse)
}

//UpdateNickname 更新昵称
func (us *UserServiceImpl) UpdateNickname(update *request.EditNicknameRequest) *api.JsonResult {
	username := update.Username
	nickname := update.Nickname

	//昵称长度限制
	length := len(nickname)
	if length >= 60 {
		return api.JsonError(api.NickNameTooLongErr)
	}

	client := service.UserService

	var ctx = context.Background()
	resp, _ := client.Edit(ctx, &pb.EditRequest{
		Username: username,
		Nickname: nickname,
	})
	if resp.Code != api.SUCCESS {
		return api.Json(int(resp.Code), resp.Msg, nil)
	}
	return api.JsonSuccess()
}

//UpdateProfile 更新头像
func (us *UserServiceImpl) UpdateProfile(update *request.UploadProfileRequest) *api.JsonResult {
	username := update.Username
	profile := update.Profile

	//文件大小验证校验
	size := profile.Size
	if size == 0 || size > 8*1024*1024 {
		logs.Warn("UpdateProfile , username: %s  , filesize error, size: %v", username, size)
		return api.JsonError(api.ProfileSizeErr)
	}

	//文件类型后缀校验
	ext := path.Ext(profile.Filename)
	if !util.In(ext, FileExt) {
		return api.JsonError(api.ProfileTypeErr)
	}

	u := uuid2.New()
	fileName := strings.TrimSuffix(profile.Filename, ext)
	imageName := fileName + "_" + u.String() + ext

	//// save
	fullPath := UploadPath + imageName
	if err := util.SaveUploadedFile(profile, fullPath); err != nil {
		logs.Error("UpdateProfile ,%v -- Failed to save file, err: %v", username, err.Error())
		return api.JsonError(api.ProfileUploadErr)
	}

	// step 3 : update picture info
	profileURL := "/" + fullPath

	client := service.UserService

	var ctx = context.Background()
	resp, _ := client.Edit(ctx, &pb.EditRequest{
		Username: username,
		Profile:  profileURL,
	})
	if resp.Code != api.SUCCESS {
		return api.Json(int(resp.Code), resp.Msg, nil)
	}
	return api.JsonSuccess()
}

//RefreshToken 客户端刷新token
func (us *UserServiceImpl) RefreshToken(username string) *api.JsonResult {
	token, _ := util.GeneratorJwt(username)
	refreshToken, _ := util.GeneratorJwt(username)
	result := map[string]string{
		"username":     username,
		"token":        token,
		"refreshToken": refreshToken,
	}
	return api.JsonData(result)
}
